package org.loofer.uiframework.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import org.loofer.ext.Ext;
import org.loofer.uiframework.R;
import java.util.Collections;
import java.util.List;

public abstract class DataListBaseAdapter<DATA, HOLD> extends BaseAdapter {
    private List<DATA> mDataList = Collections.emptyList();
    private final LayoutInflater mLayoutInflater = LayoutInflater.from(Ext.getContext());

    protected abstract void onBindViewHolder(HOLD hold, DATA data, int i);

    protected abstract View onCreateItemView(LayoutInflater layoutInflater, ViewGroup viewGroup, int i);

    protected abstract HOLD onCreateViewHold(View view);

    public void setData(List<DATA> dataList) {
        this.mDataList = dataList;
        notifyDataSetChanged();
    }

    public void appendData(List<DATA> dataList) {
        this.mDataList.addAll(dataList);
        notifyDataSetChanged();
    }

    public List<DATA> getDataList() {
        return this.mDataList;
    }

    public int getCount() {
        return this.mDataList.size();
    }

    public DATA getItem(int position) {
        return this.mDataList.get(position);
    }

    public long getItemId(int position) {
        return 0;
    }

    public final View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = onCreateItemView(this.mLayoutInflater, parent, position);
            convertView.setTag(R.id.uif_tag_view_holder, onCreateViewHold(convertView));
        }
        onBindViewHolder(convertView.getTag(R.id.uif_tag_view_holder), getItem(position), position);
        return convertView;
    }

    public void refreshItemData(DATA newData) {
        List<DATA> currentDataList = getDataList();
        for (int i = 0; i < currentDataList.size(); i++) {
            DATA old = currentDataList.get(i);
            if (old.equals(newData)) {
                currentDataList.remove(old);
                currentDataList.add(i, newData);
                notifyDataSetChanged();
                return;
            }
        }
    }
}
